package com.zkca.xf.ui.activity.personprotect;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.JobLBean;
import com.zkca.xf.model.javabean.uploadbean.RequestInspect;
import com.zkca.xf.presenter.JobCheckpresenter;
import com.zkca.xf.ui.adapter.CheckBoxAdapter;
import com.zkca.xf.ui.customview.MyListView;
import com.zkca.xf.utils.PopWindowUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.JobCheckView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

import static com.zkca.xf.ui.activity.personprotect.DeviceaddAct.convertIconToString;

public class JobCheckActivity extends BaseTitleActivity implements View.OnClickListener, TakePhoto.TakeResultListener, InvokeListener, JobCheckView {

    @BindView(R.id.jobid)
    TextView jobid;
    @BindView(R.id.devid)
    TextView devid;
    @BindView(R.id.devname)
    TextView devname;
    @BindView(R.id.installposition)
    TextView installposition;
    @BindView(R.id.listcheck)
    MyListView listcheck;
    @BindView(R.id.comment)
    EditText comment;
    @BindView(R.id.imagadd)
    ImageView imagadd;
    @BindView(R.id.imaglinear)
    LinearLayout imaglinear;
    @BindView(R.id.beganup)
    Button beganup;
    @BindView(R.id.imagandtext)
    LinearLayout imagandtext;
    @BindView(R.id.header_bar_photo_back)
    ImageView headerBarPhotoBack;
    @BindView(R.id.header_bar_photo_delete)
    ImageView headerBarPhotoDelete;
    @BindView(R.id.bigimage)
    ImageView bigimage;
    @BindView(R.id.ll_bigimage)
    LinearLayout llBigimage;
    @BindView(R.id.checkjob)
    ScrollView checkjob;

    private CheckBoxAdapter adapter;
    private List<String> typeItem;//巡检内容
    private List<String> ischecktypeItem = new ArrayList<>();//选中的检查内容

    private StringBuffer stringBuffer;//选中问题的描述

    private String commen; //输入框内容

    private String error; //提交后台的描述（选中+ 输入框）


    private View pop_phone;
    private TextView tv_photo_cancel, tv_photo_album, tv_photograph;
    private InvokeParam invokeParam;
    private Uri imageUri;//压缩后图片保存路径
    private TakePhoto takePhoto;
    private File file;
    private List<File> imageFiles = new ArrayList<>();//需要上传的文件集合
    private final int MAXNUM = 1;//最多上传图片数
    //被放大的那张图的file，也是可能会被删的图片
    private File tempFile;
    //被放大的图在picContainer中的位置
    private int index;
    private RequestBody imageBody;
    ArrayList<TImage> images;
    private RequestInspect requestInspect;
    int taskId;
    int jobId;
    private JobCheckpresenter jobCheckpresenter;
    String devId, devStatues, devimage4;
    private Dialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job_check);
        ButterKnife.bind(this);
        initPop_phone();
        jobCheckpresenter = new JobCheckpresenter(this, this);

        setTitleText("作业提交");
        setleftTextVisibility(true);
        setleftImgVisibility(true);

        loadingDialog = new Dialog(mContext);
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialogloading, null);
        //将自定义布局设置进去
        loadingDialog.setContentView(dialogView);
        loadingDialog.setCanceledOnTouchOutside(false);


        Intent intent = getIntent();
        JobLBean.DataBean jobbean = (JobLBean.DataBean) intent.getSerializableExtra("jobbean");

        jobId = jobbean.getJobId();//作业编号
        devId = jobbean.getDevId();//设备编号
        String devName = jobbean.getDevName();//设备名称
        String installPosition1 = jobbean.getInstallPosition();//设备地点
        typeItem = jobbean.getTypeItem();//检查内容
        taskId = jobbean.getTaskId();//任务ID
        jobid.setText(jobId + "");
        devid.setText(devId);
        devname.setText(devName);
        installposition.setText(installPosition1);

        adapter = new CheckBoxAdapter(typeItem, mContext);
        listcheck.setAdapter(adapter);

        imagadd.setOnClickListener(this);
        beganup.setOnClickListener(this);
        headerBarPhotoBack.setOnClickListener(this);//大图退出
        headerBarPhotoDelete.setOnClickListener(this);//图片删除

//        compressConfig = new CompressConfig.Builder().setMaxSize(500 * 1024).setMaxPixel(800).create();


        stringBuffer = new StringBuffer();
        listcheck.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                // 改变CheckBox的状态
                CheckBox itemCb = (CheckBox) view.findViewById(R.id.item_cb);
                itemCb.toggle();
                // 将CheckBox的选中状况记录下来
                CheckBoxAdapter.getIsSelected().put(position, itemCb.isChecked());
                //Device_cai.ListBean listBean = list.get(position);
                String s = typeItem.get(position);
                if (itemCb.isChecked() == true) {
                    ischecktypeItem.add(s);
                } else {
                    for (int i = 0; i < ischecktypeItem.size(); i++) {
                        if (s.equals(ischecktypeItem.get(i))) {
                            ischecktypeItem.remove(i);
                        }
                    }
                }


                if (ischecktypeItem.size() == 0) {
                    //imagandtext.setVisibility(View.GONE);
                } else {
                    //imagandtext.setVisibility(View.VISIBLE);
                }
            }
        });
        //listcheck.
        // initUpData();
    }

    private void initPop_phone() {

        pop_phone = LayoutInflater.from(this).inflate(R.layout.pop_head, null, false);
        tv_photo_cancel = (TextView) pop_phone.findViewById(R.id.tv_photo_cancel);
        tv_photo_album = (TextView) pop_phone.findViewById(R.id.tv_photo_album);
        tv_photograph = (TextView) pop_phone.findViewById(R.id.tv_photograph);
        tv_photo_cancel.setOnClickListener(this);
        tv_photo_album.setOnClickListener(this);
        tv_photograph.setOnClickListener(this);
    }

    private void initDvData() {
        Map map = new HashMap<String, Object>();
        map.put("taskId", taskId + "");
        map.put("jobId", jobId + "");
        map.put("devId", devId);
        map.put("devStatus", devStatues);
        map.put("comment", error);
        if (ischecktypeItem.size() == 0) {

        } else {
            map.put("devImage4", devimage4);
        }

        requestInspect = new RequestInspect();
        requestInspect.setParam(map);
        requestInspect.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestInspect.setAction(5);
        requestInspect.setTimeStamp(TimeUtils.getTime());
        requestInspect.setSign(MyApplication.getInstance().generateDvSign(requestInspect));
        jobCheckpresenter.submitJob(requestInspect);
    }

    private void initUpData() {
        beganup.setClickable(false);

        if (ischecktypeItem.size() == 0) { //设备安全
            if (TextUtils.isEmpty(comment.getText())) {
                error = "";
            } else {//添加输入框内容
                error = "情况说明：" + comment.getText().toString();
            }
            devStatues = "0";
            loadingDialog.show();
        } else {//设备故障
            if (imageFiles.size() == 0) {
                ToastUtils.show(mContext, "请添加现场图片");
                beganup.setClickable(true);
                return;
            }
            loadingDialog.show();
            for (int i = 0; i < ischecktypeItem.size(); i++) {
                stringBuffer.append((i + 1) + "." + ischecktypeItem.get(i) + "\n");
            }

            if (TextUtils.isEmpty(comment.getText())) {//未添加输入框内容
                error = stringBuffer.toString();
            } else {//添加输入框内容
                error = "情况说明：" + comment.getText().toString() + "\n" + stringBuffer.toString();

            }


            File file = imageFiles.get(0);
            String absolutePath = file.getAbsolutePath();
            Bitmap bitmap = BitmapFactory.decodeFile(absolutePath);
            String s = convertIconToString(bitmap);
            devimage4 = s;
            devStatues = "1";
        }

        initDvData();

    }

    public static String convertIconToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imagadd:
                PopWindowUtil.showPopWindow(this, pop_phone, checkjob);
                break;

            case R.id.tv_photo_cancel:
                PopWindowUtil.popupWindow.dismiss();
                break;
            case R.id.tv_photo_album://从相册

                PopWindowUtil.popupWindow.dismiss();
                takePhoto = getTakePhoto();
                configCompress(takePhoto);
                int maxNum = MAXNUM - imageFiles.size();
                takePhoto.onPickMultipleWithCrop(maxNum, getCropOptions());
                break;
            case R.id.tv_photograph://拍照
                file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists())
                    file.getParentFile().mkdirs();
                imageUri = Uri.fromFile(file);
                PopWindowUtil.popupWindow.dismiss();
                takePhoto = getTakePhoto();
                configCompress(takePhoto);
                takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                break;
            case R.id.header_bar_photo_back:
                llBigimage.setVisibility(View.GONE);
                setTitleBarVisibility(true);
                checkjob.setVisibility(View.VISIBLE);
                break;
            case R.id.header_bar_photo_delete:
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示")
                        .setMessage("要删除这张照片吗?")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                builder.create().dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                //从集合中移除该图片
                                imageFiles.remove(index);
                                if (imageFiles.size() >= MAXNUM) {
                                    imagadd.setVisibility(View.GONE);
                                } else {
                                    imagadd.setVisibility(View.VISIBLE);
                                }
                                //从容器中移除该图片
                                imaglinear.removeView(imaglinear.getChildAt(index));
                                llBigimage.setVisibility(View.GONE);
                                setTitleBarVisibility(true);
                                checkjob.setVisibility(View.VISIBLE);
                            }
                        }).show();
                break;
            case R.id.beganup:
                initUpData();
                break;
            default:
                if (view instanceof ImageView) {
                    tempFile = (File) view.getTag();
                    //获取被放大的图在picContainer中的位置
                    index = imaglinear.indexOfChild(view);
                    //显示大图
                    llBigimage.setVisibility(View.VISIBLE);
                    checkjob.setVisibility(View.GONE);

                    setTitleBarVisibility(false);
                    Drawable drawable = ((ImageView) view).getDrawable();
                    bigimage.setImageDrawable(drawable);
                    //进场动画
                }
                break;
        }
    }

    /**
     * 裁剪
     *
     * @return
     */
    private CropOptions getCropOptions() {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setOutputX(1000).setOutputY(1000);//裁剪框宽高
        builder.setWithOwnCrop(true);
        return builder.create();
    }


    /**
     * 压缩
     *
     * @param takePhoto
     */
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;

        config = new CompressConfig.Builder().setMaxSize(500 * 1024).setMaxPixel(800).create();

        takePhoto.onEnableCompress(config, true);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }


    @Override
    public void takeSuccess(TResult result) {
        images = result.getImages();

        //图片的布局参数
        int size = (int) getResources().getDimension(R.dimen.size_110);
        int padding = (int) getResources().getDimension(R.dimen.padding_10);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
        params.rightMargin = padding;
        TImage tImage = images.get(0);
        for (int i = 0; i < images.size(); i++) {
            String compressPath = images.get(i).getOriginalPath();
            ImageView iv = new ImageView(this);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(this).load(compressPath).into(iv);

            File file = new File(compressPath);
            //给每个imageview设置一个File的Tag，方便在删除的时候用
            iv.setTag(file);
            iv.setOnClickListener(this);
            imageFiles.add(file);

            if (imageFiles.size() >= MAXNUM) {
                imagadd.setVisibility(View.GONE);
            }
            imaglinear.addView(iv, imaglinear.getChildCount() - 1);
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {
        ToastUtils.show(mContext, msg);

        Intent intent = new Intent(mContext, Job_LActivity.class);
        intent.putExtra("taskId", taskId);
        startActivity(intent);
        finish();
    }

    @Override
    public void upJob(JobLBean s) {
//        if (s.getResult()==0){
//            ToastUtils.show(mContext,s.getInfo());
//        }
        ToastUtils.show(mContext, s.getInfo());
        Intent intent = new Intent(mContext, Job_LActivity.class);
        intent.putExtra("taskId", taskId);
        startActivity(intent);
        finish();

    }
}
